package net.guerlab.ucenter.client.handle;

import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.guerlab.commons.encrypt.AuthCodeHelper;
import net.guerlab.commons.encrypt.MD5Helper;
import net.guerlab.ucenter.client.entity.Config;

public class ClientHandle {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientHandle.class);

    protected Config config;

    protected String module;

    protected String action;

    protected Map<String, Object> args;
    
    ClientHandle() {
    }

    public String apiUrl(String extra) {
        return config.getApi() + "/index.php?" + apiRequestData(extra);
    }

    private String apiRequestData(String extra) {
        return "m=" + module + "&a=" + action + "&inajax=2&release=" + Config.CLIENT_RELEASE + "&input=" + apiInput()
                + "&appid=" + config.getAppId() + getString(extra);
    }

    private String apiInput() {
        String code = AuthCodeHelper.encode(getArgsString() + "&agent=" + MD5Helper.encode("Java/1.8.0_91") + "&time=" + time(),
                config.getKey(), 86400);

        return urlencode(code);
    }

    private String getArgsString() {
        if (args == null || args.isEmpty()) {
            return "";
        }
        
        StringBuffer s = new StringBuffer();
        String sep = "";
        for (String k : args.keySet()) {
            Object v = args.get(k);
            k = urlencode(k);
            
            if (v != null && v instanceof Map<?, ?>) {
                String s2 = "";
                String sep2 = "";
                
                @SuppressWarnings("unchecked")
                Map<String,Object> _v = (Map<String,Object>) v;
                
                for(String k2 : _v.keySet() ){
                    Object v2 = _v.get(k2);
                    k2 = urlencode(k2);
                    s2 += sep2 + "{" + k + "}[" + k2 + "]=" + urlencode( String.valueOf( v2 ));
                    sep2 = "&";
                }
                
                s.append(sep).append(s2);
            } else {
                s.append(sep).append(k).append("=").append(urlencode(String.valueOf(v)));
            }
            sep = "&";
        }
        
        return s.toString();
    }
    
    private static String urlencode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            return "";
        }  
    }

    private static String getString(String string) {
        return StringUtils.isBlank(string) ? "" : string;
    }

    private static long time() {
        return System.currentTimeMillis() / 1000;
    }
}
